package com.springboot.file.util;

import org.apache.poi.xwpf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 模板生成器 - 在应用启动时自动生成Word模板文件
 */
@Component
public class TemplateGenerator implements CommandLineRunner {
    private static final Logger log = LoggerFactory.getLogger(TemplateGenerator.class);
    
    @Value("${document.template.path:classpath:templates/}")
    private String templatePath;
    
    @Override
    public void run(String... args) throws Exception {
        try {
            generateTemplates();
        } catch (Exception e) {
            log.error("生成模板文件时发生错误", e);
        }
    }
    
    /**
     * 生成模板文件
     */
    private void generateTemplates() throws Exception {
        log.info("开始生成Word模板文件...");
        
        // 确定模板目录路径
        String dirPath = getTemplateDirPath();
        Path dir = Paths.get(dirPath);
        
        // 确保目录存在
        if (!Files.exists(dir)) {
            Files.createDirectories(dir);
            log.info("已创建模板目录: {}", dirPath);
        }
        
        // 检查现有模板并生成缺失的模板
        Path sampleTemplatePath = dir.resolve("sample_template.docx");
        Path contractTemplatePath = dir.resolve("contract_template.docx");
        
        if (!Files.exists(sampleTemplatePath)) {
            generateSampleTemplate(sampleTemplatePath.toFile());
            log.info("已生成示例模板: {}", sampleTemplatePath);
        } else {
            log.info("示例模板已存在: {}", sampleTemplatePath);
        }
        
        if (!Files.exists(contractTemplatePath)) {
            generateContractTemplate(contractTemplatePath.toFile());
            log.info("已生成合同模板: {}", contractTemplatePath);
        } else {
            log.info("合同模板已存在: {}", contractTemplatePath);
        }
        
        log.info("模板文件生成完成");
    }
    
    /**
     * 获取模板目录的物理路径
     */
    private String getTemplateDirPath() {
        if (templatePath.startsWith("classpath:")) {
            try {
                String resourcePath = templatePath.substring("classpath:".length());
                ClassPathResource resource = new ClassPathResource(resourcePath);
                return resource.getFile().getAbsolutePath();
            } catch (Exception e) {
                // 如果从classpath获取失败，使用相对路径
                return "src/main/resources/templates";
            }
        } else {
            return templatePath;
        }
    }
    
    /**
     * 生成示例模板
     */
    private void generateSampleTemplate(File file) throws Exception {
        XWPFDocument document = new XWPFDocument();
        
        // 标题
        XWPFParagraph titleParagraph = document.createParagraph();
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleRun = titleParagraph.createRun();
        titleRun.setText("${title}");
        titleRun.setBold(true);
        titleRun.setFontSize(18);
        
        // 空行
        document.createParagraph();
        
        // 作者和日期行
        XWPFParagraph authorDateParagraph = document.createParagraph();
        XWPFRun authorRun = authorDateParagraph.createRun();
        authorRun.setText("作者：${author}");
        
        // 添加制表符
        for (int i = 0; i < 10; i++) {
            authorRun.addTab();
        }
        
        authorRun.setText("日期：${date}");
        
        // 空行
        document.createParagraph();
        
        // 客户信息部分
        XWPFParagraph customerTitleParagraph = document.createParagraph();
        XWPFRun customerTitleRun = customerTitleParagraph.createRun();
        customerTitleRun.setText("客户信息：");
        customerTitleRun.setBold(true);
        
        XWPFParagraph customerNameParagraph = document.createParagraph();
        customerNameParagraph.setIndentationFirstLine(480); // 首行缩进
        XWPFRun customerNameRun = customerNameParagraph.createRun();
        customerNameRun.setText("客户名称：${customerName}");
        
        XWPFParagraph customerIdParagraph = document.createParagraph();
        customerIdParagraph.setIndentationFirstLine(480); // 首行缩进
        XWPFRun customerIdRun = customerIdParagraph.createRun();
        customerIdRun.setText("客户编号：${customerId}");
        
        // 空行
        document.createParagraph();
        
        // 正文内容部分
        XWPFParagraph contentTitleParagraph = document.createParagraph();
        XWPFRun contentTitleRun = contentTitleParagraph.createRun();
        contentTitleRun.setText("正文内容：");
        contentTitleRun.setBold(true);
        
        XWPFParagraph contentParagraph = document.createParagraph();
        contentParagraph.setIndentationFirstLine(480); // 首行缩进
        XWPFRun contentRun = contentParagraph.createRun();
        contentRun.setText("${content}");
        
        // 空行
        document.createParagraph();
        document.createParagraph();
        
        // 签名行
        XWPFParagraph signatureParagraph = document.createParagraph();
        XWPFRun signatureRun = signatureParagraph.createRun();
        signatureRun.setText("签名：________________");
        
        // 添加制表符
        for (int i = 0; i < 8; i++) {
            signatureRun.addTab();
        }
        
        signatureRun.setText("审核：________________");
        
        // 保存文档
        try (FileOutputStream out = new FileOutputStream(file)) {
            document.write(out);
        }
    }
    
    /**
     * 生成合同模板
     */
    private void generateContractTemplate(File file) throws Exception {
        XWPFDocument document = new XWPFDocument();
        
        // 标题
        XWPFParagraph titleParagraph = document.createParagraph();
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleRun = titleParagraph.createRun();
        titleRun.setText("服务合同");
        titleRun.setBold(true);
        titleRun.setFontSize(18);
        
        // 空行
        document.createParagraph();
        
        // 合同编号和日期行
        XWPFParagraph contractIdDateParagraph = document.createParagraph();
        XWPFRun contractIdDateRun = contractIdDateParagraph.createRun();
        contractIdDateRun.setText("合同编号：${contractId}");
        
        // 添加制表符
        for (int i = 0; i < 8; i++) {
            contractIdDateRun.addTab();
        }
        
        contractIdDateRun.setText("日期：${date}");
        
        // 空行
        document.createParagraph();
        
        // 甲方信息
        XWPFParagraph partyAParagraph = document.createParagraph();
        XWPFRun partyARun = partyAParagraph.createRun();
        partyARun.setText("甲方（供应商）：${companyName}");
        
        XWPFParagraph partyARepParagraph = document.createParagraph();
        XWPFRun partyARepRun = partyARepParagraph.createRun();
        partyARepRun.setText("代表人：${companyRep}");
        
        XWPFParagraph partyAContactParagraph = document.createParagraph();
        XWPFRun partyAContactRun = partyAContactParagraph.createRun();
        partyAContactRun.setText("联系方式：${companyContact}");
        
        // 空行
        document.createParagraph();
        
        // 乙方信息
        XWPFParagraph partyBParagraph = document.createParagraph();
        XWPFRun partyBRun = partyBParagraph.createRun();
        partyBRun.setText("乙方（客户）：${customerName}");
        
        XWPFParagraph partyBRepParagraph = document.createParagraph();
        XWPFRun partyBRepRun = partyBRepParagraph.createRun();
        partyBRepRun.setText("代表人：${customerRep}");
        
        XWPFParagraph partyBContactParagraph = document.createParagraph();
        XWPFRun partyBContactRun = partyBContactParagraph.createRun();
        partyBContactRun.setText("联系方式：${customerContact}");
        
        // 空行
        document.createParagraph();
        
        // 合同条款
        // 一、服务内容
        XWPFParagraph serviceParagraph = document.createParagraph();
        XWPFRun serviceRun = serviceParagraph.createRun();
        serviceRun.setText("一、服务内容");
        serviceRun.setBold(true);
        
        XWPFParagraph serviceContentParagraph = document.createParagraph();
        serviceContentParagraph.setIndentationFirstLine(480); // 首行缩进
        XWPFRun serviceContentRun = serviceContentParagraph.createRun();
        serviceContentRun.setText("${serviceContent}");
        
        // 空行
        document.createParagraph();
        
        // 二、服务期限
        XWPFParagraph termParagraph = document.createParagraph();
        XWPFRun termRun = termParagraph.createRun();
        termRun.setText("二、服务期限");
        termRun.setBold(true);
        
        XWPFParagraph startDateParagraph = document.createParagraph();
        startDateParagraph.setIndentationFirstLine(480); // 首行缩进
        XWPFRun startDateRun = startDateParagraph.createRun();
        startDateRun.setText("服务起始日：${startDate}");
        
        XWPFParagraph endDateParagraph = document.createParagraph();
        endDateParagraph.setIndentationFirstLine(480); // 首行缩进
        XWPFRun endDateRun = endDateParagraph.createRun();
        endDateRun.setText("服务截止日：${endDate}");
        
        // 空行
        document.createParagraph();
        
        // 三、服务费用
        XWPFParagraph feeParagraph = document.createParagraph();
        XWPFRun feeRun = feeParagraph.createRun();
        feeRun.setText("三、服务费用");
        feeRun.setBold(true);
        
        XWPFParagraph amountParagraph = document.createParagraph();
        amountParagraph.setIndentationFirstLine(480); // 首行缩进
        XWPFRun amountRun = amountParagraph.createRun();
        amountRun.setText("合同总金额：${amount}元");
        
        XWPFParagraph paymentMethodParagraph = document.createParagraph();
        paymentMethodParagraph.setIndentationFirstLine(480); // 首行缩进
        XWPFRun paymentMethodRun = paymentMethodParagraph.createRun();
        paymentMethodRun.setText("付款方式：${paymentMethod}");
        
        // 空行
        document.createParagraph();
        
        // 四、甲方权利与义务
        XWPFParagraph partyAObligationsParagraph = document.createParagraph();
        XWPFRun partyAObligationsRun = partyAObligationsParagraph.createRun();
        partyAObligationsRun.setText("四、甲方权利与义务");
        partyAObligationsRun.setBold(true);
        
        XWPFParagraph providerObligationsParagraph = document.createParagraph();
        providerObligationsParagraph.setIndentationFirstLine(480); // 首行缩进
        XWPFRun providerObligationsRun = providerObligationsParagraph.createRun();
        providerObligationsRun.setText("${providerObligations}");
        
        // 空行
        document.createParagraph();
        
        // 五、乙方权利与义务
        XWPFParagraph partyBObligationsParagraph = document.createParagraph();
        XWPFRun partyBObligationsRun = partyBObligationsParagraph.createRun();
        partyBObligationsRun.setText("五、乙方权利与义务");
        partyBObligationsRun.setBold(true);
        
        XWPFParagraph customerObligationsParagraph = document.createParagraph();
        customerObligationsParagraph.setIndentationFirstLine(480); // 首行缩进
        XWPFRun customerObligationsRun = customerObligationsParagraph.createRun();
        customerObligationsRun.setText("${customerObligations}");
        
        // 空行
        document.createParagraph();
        
        // 六、保密条款
        XWPFParagraph confidentialityParagraph = document.createParagraph();
        XWPFRun confidentialityRun = confidentialityParagraph.createRun();
        confidentialityRun.setText("六、保密条款");
        confidentialityRun.setBold(true);
        
        XWPFParagraph confidentialityContentParagraph = document.createParagraph();
        confidentialityContentParagraph.setIndentationFirstLine(480); // 首行缩进
        XWPFRun confidentialityContentRun = confidentialityContentParagraph.createRun();
        confidentialityContentRun.setText("${confidentiality}");
        
        // 空行
        document.createParagraph();
        
        // 七、违约责任
        XWPFParagraph liabilityParagraph = document.createParagraph();
        XWPFRun liabilityRun = liabilityParagraph.createRun();
        liabilityRun.setText("七、违约责任");
        liabilityRun.setBold(true);
        
        XWPFParagraph liabilityContentParagraph = document.createParagraph();
        liabilityContentParagraph.setIndentationFirstLine(480); // 首行缩进
        XWPFRun liabilityContentRun = liabilityContentParagraph.createRun();
        liabilityContentRun.setText("${liability}");
        
        // 空行
        document.createParagraph();
        
        // 八、其他条款
        XWPFParagraph otherTermsParagraph = document.createParagraph();
        XWPFRun otherTermsRun = otherTermsParagraph.createRun();
        otherTermsRun.setText("八、其他条款");
        otherTermsRun.setBold(true);
        
        XWPFParagraph otherTermsContentParagraph = document.createParagraph();
        otherTermsContentParagraph.setIndentationFirstLine(480); // 首行缩进
        XWPFRun otherTermsContentRun = otherTermsContentParagraph.createRun();
        otherTermsContentRun.setText("${otherTerms}");
        
        // 空行
        document.createParagraph();
        document.createParagraph();
        
        // 签名行
        XWPFParagraph signatureParagraph = document.createParagraph();
        XWPFRun signatureRun = signatureParagraph.createRun();
        signatureRun.setText("甲方（盖章）：                      乙方（盖章）：");
        
        XWPFParagraph signatureRepParagraph = document.createParagraph();
        XWPFRun signatureRepRun = signatureRepParagraph.createRun();
        signatureRepRun.setText("代表签字：                          代表签字：");
        
        XWPFParagraph signatureDateParagraph = document.createParagraph();
        XWPFRun signatureDateRun = signatureDateParagraph.createRun();
        signatureDateRun.setText("日期：                              日期：");
        
        // 保存文档
        try (FileOutputStream out = new FileOutputStream(file)) {
            document.write(out);
        }
    }
} 